﻿using Digitalmes.Services.Data;
using Digitalmes.Signals;
using MediatR;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace Digitalmes.EventHandler
{
    public  class EntryHandler :AbstractHandler<EntrySignal>
    {

        public override async  Task<HandleResult> Handle(EntrySignal request, CancellationToken cancellationToken)
        {
            
            string sn=request.Sn;   






            string productCode=request.ProductCode;

            string opCode = "工位不能为空";

            //进站记录
            string msg = string.Format("[进站请求数据] {SN}, 工位：{OpCode}，数据：{Message}",
             sn ?? "",
            request.SignalTag.DriverGroup,
             JsonSerializer.Serialize(request.SignalTag?.TagGroup?.Select(s => new { s.Name, s.Address, s.Value })));

            Log.Information(msg);


            ///产品不能为空 工装识别码 
            if (string.IsNullOrEmpty(productCode))
            {
                return LogAndReturn(ErrorCode.E1002, opCode);
            }

         
          


           

            ///条码不能为空   
            if (string.IsNullOrEmpty(sn))
            {
                return LogAndReturn(ErrorCode.E1001,opCode);
            }

           



            var serive=GetService<EntryService>();

            var response=await serive.GetServiceResponse(request);

            return HandleResult.Ok(response);    
        }

        /// <summary>
        /// 进站日志记录
        /// </summary>
        /// <param name="ErrorCode"></param>
        /// <param name="opCode"></param>
        /// <returns></returns>
        private HandleResult LogAndReturn(ErrorCode ErrorCode, string opCode)
        {
            var result = HandleResult.Error(ErrorCode);
            string msg = string.Format("[进站响应] 工位：{OpCode}，状态: {State}, 消息: [{InnerErrorCode}]-{ErrMessage}",
                    opCode,
                    result.State.ToString(),
                    result.InnerErrorCode.ToString(),
                    result.GetErrorMessage());

            Log.Information(msg);

            return result;
        }
    }
}
